#include <libxml/parser.h>
#include <libxml/xmlschemas.h>

#include <stdio.h>
#include <string.h>
#include <sysexits.h>
#include <syslog.h>
#include <ctype.h>
#include <unistd.h>

#include "common.h"

const char *const append = "/KeyInfo.xml";

int main(int argc, char **argv) {
  xmlDocPtr doc;
  char *file, *ptr;
  xmlNodePtr root;
  xmlSchemaParserCtxtPtr parser;
  xmlSchemaValidCtxtPtr vctx;
  xmlSchemaPtr schemap;
  
  openlog("validate-keyinfo", LOG_PID|LOG_PERROR, LOG_AUTHPRIV);
  if(argc != 2) {
    syslog(LOG_WARNING, "called with argc == %d, invalid", argc);
    exit(EX_USAGE);
  }
#if 0
  for(ptr = argv[1]; *ptr; ptr++)
    if(!isxdigit(*ptr)) {
      syslog(LOG_WARNING, "invalid character in filename");
      exit(EX_USAGE);
    }
  if(chdir("/home/sessions")) {
    syslog(LOG_WARNING, "called with argc == %d, invalid", argc);
    exit(EX_SOFTWARE);
  }
  file = alloca(strlen(argv[1]) + strlen(append) + 1);
  strcpy(file, argv[1]);
  strcat(file, append);
#else
  file = argv[1];
#endif
  libSetup();
  doc = xmlParseFile(file);
  if(!doc) {
    syslog(LOG_WARNING, "Not parseable as XML");
    exit(EX_DATAERR);
  }
  root = xmlDocGetRootElement(doc);
  if(!root) {
    syslog(LOG_WARNING, "No root element in document");
    exit(EX_DATAERR);
  }

  parser = xmlSchemaNewParserCtxt(DATADIR "/xmldsig-core-schema.xsd");
  if(!parser) {
    syslog(LOG_WARNING, "Couldn't load schema to validate document");
    exit(EX_DATAERR);
  }

  schemap = xmlSchemaParse(parser);
  if(!parser) {
    syslog(LOG_WARNING, "Couldn't parse schema");
    exit(EX_DATAERR);
  }

  vctx = xmlSchemaNewValidCtxt(schemap);
  if(!vctx) {
    syslog(LOG_WARNING, "Couldn't create validation context");
    exit(EX_DATAERR);
  }


  if(xmlSchemaValidateDoc(vctx, doc)) {
    syslog(LOG_WARNING, "Document failed to validate");
    exit(EX_DATAERR);
  }

  return 0;
}
